package me.szlx.thing.bundle;

import me.szlx.thing.Thing;
import me.szlx.thing.parser.ThingParser;
import me.szlx.thing.parser.ThingParserConfig;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class GenericThingBundle<T extends Thing> extends AbstractThingBundle<T> implements ThingBundle<T> {
    private String prefix;

    public GenericThingBundle() {
    }

    public GenericThingBundle(String resource) {
        setResource(resource);
    }

    @Override
    protected List<T> doGetAll(String resource) {
        InputStream resourceStream = AbstractThingBundle.class.getClassLoader().getResourceAsStream(resource);
        if (resourceStream == null) {
            logger.debug("未找到资源文件：{}", resource);
            return new ArrayList<T>();
        }
        return getParser(getResourceFormat(resource)).parse(resourceStream).getAll();
    }

    public String getResourceFormat(String resource) {
        int dotIndex = resource.lastIndexOf(".");
        return dotIndex != -1 ? resource.substring(dotIndex + 1) : "";
    }

    private ThingParser<T> getParser(String resourceFormat) {
        return ThingParser.getParser(
                ThingParserConfig.newInstance()
                        .format(resourceFormat)
                        .thingCreator(getThingCreator())
                        .traitCreator(getTraitCreator())
                        .prefix(prefix));
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
}
